<?php

namespace app\script\controller;
use app\common\controller\Common;
use think\Db;
use com\Wave;

class Script extends Common
{
    public $maindir = "/home/wwwroot/default/data/";
    public $speech0 = "";
    public $speech1 = "";
    public $speech2 = "";
    public $userhome = "";
    public $user_id = "";
    public $temp = "";
    public function __construct()
    {
        parent::__construct();
        // $this->user_id = 54321;
        // $this->user_id = input('user_id/d', 1);
        $this->temp = $this->maindir . "temp/" . $this->user_id . "";
        $this->speech0 = $this->maindir . "speech0/" . $this->user_id . "";
        $this->speech1 = $this->maindir . "speech1/" . $this->user_id . "";
        $this->speech2 = $this->maindir . "speech2/" . $this->user_id . "";
    }
   
    public function lvsr_task(){
        $get = input('');
        $start = $get['start'] ? intval($get['start']) : 0;
        $pagesize = intval($get['pagesize']) ? intval($get['pagesize']) : 20;
        $offset = $start . "," . $pagesize;
        $where['lvsr_status'] = 1;
        $where['type'] = 0;
        $total = Db::name('meeting_speech')->where($where)->count();
        $list = Db::name('meeting_speech')->where($where)->order('create_time desc')->limit($offset)->select();
        foreach ($list as $k => $v) {
            $list[$k]['wavpth'] = "/home/wwwroot/default/data/box-recording/" . $v['formatname'];
            //$list[$k]['wavpth'] = "/home/wwwroot/default/data/box-recording/" . substr($v['formatname'], 0, -3) . "wav";
            //$list[$k]['wavpth'] = "/home/wwwroot/default/data/speech1/box-recording/" . $v['user_id'] . "/" . substr($v['formatname'], 0, -3) . "wav";
        }
        $data['total'] = $total;
        $data['list'] = $list;
        $data['start'] = $start;
        $data['pagesize'] = $pagesize;
      
        return json($data);

    }


    public function lvsr_start()
    { 
        $get = input('');
        $where['formatname'] = $get['_id'];
        $time = time();
        $info['lvsr_start_time'] = $time;
        $info['lvsr_status'] = 2;
        // $info['lvsr_end_time'] = $time;
        Db::name('meeting_speech')->where($where)->update($info);
        $result['msg'] = 0;
        return json($result);
    }


    
    public function lvsr_put()
    {
        $get = input('');
        $id = $get['_id'];
        if ($get['lvsr_data']) {
            $info['lvsr_status'] = 3;
            $info['lvsr_data'] = json_decode($get['lvsr_data'],true)['list'] ? $get['lvsr_data'] : '';
            //$info['lvsr_data'] = $get['lvsr_data'];
        } else {
            $info['lvsr_status'] = 2;
        }
        $info['lvsr_end_time'] = time();
        Db::name('meeting_speech')->where(array('formatname' => $id))->update($info);

        $formatname = $id;
        $res = Db::name('meeting_speech')->where(['formatname'=>$formatname])->find();
        $id = $res['id'];
        /* $url = 'http://192.168.0.192:9200/meeting/external/'.$id;
        $meeting_id = $res['meeting_id'];
        $lvsr_data = json_decode($res['lvsr_data'],1);
        $list = [];
        if(!empty($lvsr_data['list'])){
            foreach ($lvsr_data['list'] as $key => $value) {
                $ar = explode('-', $value['time']);
                $list[$key]['time'] = $ar[0];
                $list[$key]['txt'] = $value['txt']; 
            }
        }
        $rank = array_column($list, 'time');
        array_multisort($rank,SORT_ASC,$list);
        $lvsr_data = '';
        foreach ($list as $k => $v) {
            $lvsr_data.=$v['txt'];
        }
        $arr = ['meeting_id'=>$meeting_id,'lvsr_data'=>$lvsr_data];
        curl_post($url,json_encode($arr)); */
        // dump($res);
        // exit;
        $result['msg'] = 0;
        return json($result);
    }

    public function initdatahome()
    {
        @mkdir($this->temp, 0777, true);
        @mkdir($this->speech0, 0777, true);
        @mkdir($this->speech1, 0777, true);
        @mkdir($this->speech2, 0777, true);
    }
  

    public function searchDir($path)
    {
        $filesnames = scandir($path);
        foreach ($filesnames as $name) {
            if ($name == "." || $name == "..") {
                continue;
            }

            $data[] = $name;
        }
        return $data;
    }
    public function writerecorderdb($filename, $meeting_id = 0)
    {
        
       
        $where['uid'] = $this->user_id;
        $where['meeting_id'] = $meeting_id;
        $time = time();
        $fileinfo = Db::name('meeting_list')->where($where)->find();
        if (!$fileinfo) { //表示没有上传过记录
            $info['filename'] = $filename;
            $info['filenamemd5'] = md5($filename);
            $info['meeting_id'] = $meeting_id;
            $info['user_id'] = $this->user_id;
            $info['formatname'] = trim(date('YmdHis', time()) . rand(1000, 9999) . "." . substr(strrchr($filename, '.'), 1));
            $info['create_time'] = $time;
            $fileinfo_arr = explode('_',$filename);
            if(count($fileinfo_arr) == 3){
                $aisle = $fileinfo_arr[1];
            }else{
                $aisle = '99';
            }
            Db::name('meeting_list')->insert(array('meeting_id'=>$meeting_id,'name' => $meeting_id,  'ctime' => $time, 'uid' => $this->user_id));
           // $l = Db::name('meeting_list')->select();
           // var_dump($l);exit;
            //echo Db::name('meeting_list')->getlastsql();exit;
            //$recorder_id = Db::name('meeting_list')->getLastInsID();
            //$info['recorder_id'] = $recorder_id;
            $info['aisle'] = $aisle;
            Db::name('meeting_speech')->insert($info);
            $id = Db::name('meeting_speech')->getLastInsID();
            return $id;
        } else { //表示上传记录
                $subname = date('Ymdhi', $time);
                $filename = substr($filename, 0, -4) . "_" . $subname . substr($filename, -4);
                $info['filename'] = $filename;
                $info['filenamemd5'] = md5($filename);
                $info['user_id'] = $this->user_id;
                $info['meeting_id'] = $meeting_id;
                $info['formatname'] = date('YmdHis', time()) . rand(1000, 9999) . "." . substr(strrchr($filename, '.'), 1);
                $info['create_time'] = $time;
               // $info['recorder_id'] = $fileinfo['id'];
                $fileinfo_arr = explode('_',$filename);
                if(count($fileinfo_arr) == 4){
                    $info['aisle'] = $fileinfo_arr[1];
                }else{
                    $info['aisle'] = '99';
                }
                Db::name('meeting_speech')->insert($info);
                $id = Db::name('meeting_speech')->getLastInsID();
                return $id;
            
        }
    }
    public function convertformat($filename, $id)
    {
        $filename = $filename ? $filename : $_GET['filename'];
        $speech_table = Db::name('meeting_speech');
        $where['id'] = $id;
//$where['filename']=$filename;
        $fileinfo = $speech_table->where($where)->find();
        $pathinfo = pathinfo($filename);
        if ($pathinfo['extension'] == "pcm") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            system("sox -t raw -c 1 -s -b 16 -r 16000  $pcmpath -c 1 -s -r 16000 $wavpath", $return);
        } else if ($pathinfo['extension'] == "wav") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            copy($pcmpath, $wavpath);
        } else if ($pathinfo['extension'] == "mp3") {
            $sourcepath = $this->temp . "/" . $filename;
            $pcmpath = $this->speech0 . "/" . $fileinfo['formatname'];
            rename($sourcepath, $pcmpath);
            $wavpatht = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . "_t.wav";
            $wavpath = $this->speech1 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".wav";
            system("lame --mp3input --decode -m m --resample 16 " . $pcmpath . " " . $wavpatht, $return);
            system("sox " . $wavpatht . " -r 16000 -c 1 " . $wavpath, $return);
        }
        $mp3path = $this->speech2 . "/" . basename($fileinfo['formatname'], '.' . $pathinfo['extension']) . ".mp3";
        system("lame  --quiet -b 32 --resample 11  $wavpath $mp3path ", $return);
// $Mkmp=new Mkwavejson($mp3path);
        // $json=$Mkmp->mkjson();
        // file_put_contents(substr($mp3path,0,-3)."json",$json);
        $wavinfo = $this->mkjson($wavpath, substr($mp3path, 0, -3) . "json");
        $result['msg'] = "0";
        if ($fileinfo['lvsr_status'] == 3) { //表示已经转写
        } else {
            $task = "recorder_lvsr";
            $a['path'] = $wavpath;
            $a['id'] = $fileinfo['_id'];
            $info['lvsr_status'] = 0;
            //$info['seconds']=$wavinfo['seconds'];
            $info['seconds'] = $wavinfo['seconds'];
            $info['Channels'] = $wavinfo['Channels'];
            $info['SamplesPerSec'] = $wavinfo['SamplesPerSec'];
            $info['AvgBytesPerSec'] = $wavinfo['AvgBytesPerSec'];
            $info['BitsPerSample'] = $wavinfo['BitsPerSample'];
            $speech_table->where($where)->update($info);
        }
        // $this->assign('list',$list);
        //echo json_encode($result);
        // exit;
    }

    public function mkjson($file, $jsonfile)
    {

        $Mkmp = new Wave($file);
        $a = $Mkmp->wavechunk();
        $sample_count = ceil($a['seconds'] * $a['SamplesPerSec'] / 1000);
        $cmd = "wav2json $file  -s $sample_count -o " . "/home/wwwroot/default/test.json";
        //echo $cmd;exit;
        system($cmd);
        $ret = file_get_contents("/home/wwwroot/default/test.json");
        $data = json_decode($ret);
        foreach ($data->left as $key => $val) {
            $rt[$key] = $val;
        }
        file_put_contents($jsonfile, json_encode($rt));
        return $a;
    }

    public function uploadfile()
    {

        $this->initdatahome();

        $input = input('');
        $temp_dir = $this->temp;
        $path = $input['path'];
        $wav = $input['wav'];
        $meeting_id = $input['meeting_id'];
       
        if (!is_dir($temp_dir)) {
            mkdir($temp_dir, 0777, true);
        }
       

        if (!$path && !$wav) {
            return json(array('参数错误'));
        }
       //  var_dump($input);exit;
       //copy($path,$temp_dir."/".$wav);
        //echo "cp $path $temp_dir"."/".$wav;exit;
        system("cp $path $temp_dir"."/".$wav);
       
        $id = $this->createFileFromChunks($wav,$meeting_id);
        //$id = I('id');
        //自动转写
        $lvsr_type = 1;
        //$recorder = model('oldweb')->item('sanban_recorder',array('id'=>$id));
        $recorder = Db::name('meeting_speech')->where(array('id' => $id))->find();
        if (empty($recorder)) {
            return json(array('error' => '修改失败'));
        }
        if (!empty($lvsr_type)) {
            // var_dump($info);
            $info['update_time'] = time();
            $info['lvsr_status'] = 1;
            $info['lvsr_type'] = $lvsr_type;
            $r = Db::name('meeting_speech')->where(array('id' => $id))->update($info);
            //echo "qwe123";
            //$r = model('oldweb')->itemUpdate('sanban_recorder',array('id'=>$id),$info);
        }

        return $id;
    }
    
    public function uploadfile_auto($path,$wav,$meeting_id)
    {

        $this->initdatahome();

        $input = input('');
        $temp_dir = $this->temp;
       // $path = $input['path'];
        //$wav = $input['wav'];
        //$meeting_id = $input['meeting_id'];
       
        if (!is_dir($temp_dir)) {
            mkdir($temp_dir, 0777, true);
        }
       

        if (!$path && !$wav) {
            return json(array('参数错误'));
        }
       // var_dump($path);exit;
       //copy($path,$temp_dir."/".$wav);
        //echo "cp $path $temp_dir"."/".$wav;exit;
        system("cp $path $temp_dir"."/".$wav);
       
        $id = $this->createFileFromChunks($wav,$meeting_id);
        //$id = I('id');
        //自动转写
        $lvsr_type = 1;
        //$recorder = model('oldweb')->item('sanban_recorder',array('id'=>$id));
        $recorder = Db::name('meeting_speech')->where(array('id' => $id))->find();
        if (empty($recorder)) {
            return json(array('error' => '修改失败'));
        }
        if (!empty($lvsr_type)) {
            // var_dump($info);
            $info['update_time'] = time();
            $info['lvsr_status'] = 1;
            $info['lvsr_type'] = $lvsr_type;
            $r = Db::name('meeting_speech')->where(array('id' => $id))->update($info);
            //echo "qwe123";
            //$r = model('oldweb')->itemUpdate('sanban_recorder',array('id'=>$id),$info);
        }

        return $id;
    }

    public function createFileFromChunks($fileName,$meeting_id)
    {

        $id = $this->writerecorderdb($fileName,$meeting_id);

        if ($id) {
            $this->convertformat($fileName, $id);
        } else {
            $data = array('res' => 1, "info" => "存储数据错误");
            return json($data);
        }
        return $id;

    }

    public function rrmdir($dir)
    {
        if (is_dir($dir)) {
            $objects = scandir($dir);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dir . "/" . $object) == "dir") {
                        rrmdir($dir . "/" . $object);
                    } else {
                        unlink($dir . "/" . $object);
                    }
                }
            }
            reset($objects);
            rmdir($dir);
        }
    }

    public function _logupload($str)
    {
        // log to the output
        $log_str = date('d.m.Y') . ": {$str}\r\n";
        echo $log_str;
        // log to file
        if (($fp = fopen('upload_log.txt', 'a+')) !== false) {
            fputs($fp, $log_str);
            fclose($fp);
        }
    }

    public function getChunkFilename($chunkNumber, $identifier, $filename)
    {
        $temp_dir = $this->temp . '/' . $identifier;
        return $temp_dir . '' . $filename . '.part' . $chunkNumber;
    }

    public function cleanIdentifier($identifier)
    {
        return $identifier;
        //return  preg_replace('/^0-9A-Za-z_-/', '', $identifier);
    }
    //$maxFileSize = 2*1024*1024*1024;
    public function validateRequest($chunkNumber, $chunkSize, $totalSize, $identifier, $filename, $fileSize = '')
    {
        // Clean up the identifier
        //$identifier = cleanIdentifier($identifier);
        // Check if the request is sane
        if ($chunkNumber == 0 || $chunkSize == 0 || $totalSize == 0 || $identifier == 0 || $filename == "") {
            return 'non_resumable_request';
        }
        $numberOfChunks = max(floor($totalSize / ($chunkSize * 1.0)), 1);
        if ($chunkNumber > $numberOfChunks) {
            return 'invalid_resumable_request1';
        }
        // Is the file too big?
        //      if($maxFileSize && $totalSize>$maxFileSize) {
        //          return 'invalid_resumable_request2';
        //      }
        if ($fileSize != "") {
            if ($chunkNumber < $numberOfChunks && $fileSize != $chunkSize) {
                // The chunk in the POST request isn't the correct size
                return 'invalid_resumable_request3';
            }
            if ($numberOfChunks > 1 && $chunkNumber == $numberOfChunks && $fileSize != (($totalSize % $chunkSize) + $chunkSize)) {
                // The chunks in the POST is the last one, and the fil is not the correct size
                return 'invalid_resumable_request4';
            }
            if ($numberOfChunks == 1 && $fileSize != $totalSize) {
                // The file is only a single chunk, and the data size does not fit
                return 'invalid_resumable_request5';
            }
        }
        return 'valid';
    }

    public function copy_file(){
        $dir = '/home/wwwroot/default/wav';
      //  echo 1;exit;
        $files = $this->all_file($dir);
        $new_dir = '/home/wwwroot/default/wav/';
        
        if(!is_dir($new_dir)){
            mkdir($new_dir);
        }
        //var_dump($files);exit;
        foreach ($files as $value) {
            $pathinfo = pathinfo($value);
            $new_file = $new_dir.$pathinfo['basename'];
            if($pathinfo['basename']){
                $f = Db::name('files')->where(array('file_name' => $pathinfo['basename']))->find();
                if(empty($f)){
                    $arr = explode('_',$pathinfo['basename']);
                    $meeting_id = $arr[0];
                    $path = $new_file;
                    $wav = $pathinfo['basename'];
                   // var_dump($wav,$path);exit;
                    if($meeting_id && $path && $wav){
                        Db::name('files')->insert(array('file_name'=>$wav));
                        $this->uploadfile_auto($path,$wav,$meeting_id);
                    }
                  
                }
            }
        }
    }
    public function all_file($dir)
    {
        if (is_file($dir)) {
            $pathinfo = pathinfo($dir);
            if($pathinfo['extension'] == 'md5'){
                $wav = str_replace('.md5', '.wav', $f);
                if(file_exists($wav)){
                    if(file_get_contents($dir) == md5_file($wav)){
                       $this->all[] = $wav;
                    }
                }
                //var_dump($pathinfo);exit;
            }
           // $this->all[$dir] = md5_file($dir);
            return $this->all;
        }
        if (is_dir($dir)) {
            $open = opendir($dir);
            while (($file = readdir($open)) !== false) {
                if ($file != "." && $file != "..") {
                    $f = $dir . "/" . $file;
                    if (is_file($f)) {
                        $pathinfo = pathinfo($f);
                        if($pathinfo['extension'] == 'md5'){
                            $wav = str_replace('.md5', '.wav', $f);
                            if(file_exists($wav)){
                                if(file_get_contents($f) == md5_file($wav)){
                                   $this->all[] = $wav;
                                }
                            }
                            //var_dump($pathinfo);exit;
                        }
                        //$this->all[$f] = md5_file($f);
                    } elseif (is_dir($f)) {
                        $this->all_file($f);
                    }
                }
            }
        }
        return $this->all;
    }

    public function dir_file($dir)
    {
        if (is_file($dir)) {
            $pathinfo = pathinfo($dir);
            if($pathinfo['extension'] == 'md5'){
                $wav = str_replace('.md5', '.wav', $f);
                if(file_exists($wav)){
                    if(file_get_contents($dir) == md5_file($wav)){
                       $this->all[] = $wav;
                    }
                }
                //var_dump($pathinfo);exit;
            }
           // $this->all[$dir] = md5_file($dir);
            return $this->all;
        }
        if (is_dir($dir)) {
            $open = opendir($dir);
            while (($file = readdir($open)) !== false) {
                if ($file != "." && $file != "..") {
                    $f = $dir . "/" . $file;
                    
                    $row = array();
                   
                    if(is_file($f)){
                        $row['type'] = 'file';
                        $row['name'] = $file;
                    }else if(is_dir($f)){
                        $row['type'] = 'dir';
                        $row['name'] = $file;
                    }
                    $this->all[] = $row;
                    /* if (is_file($f)) {
                        $this->all[] = $f;
                        $pathinfo = pathinfo($f);
                         if($pathinfo['extension'] == 'md5'){
                            $wav = str_replace('.md5', '.wav', $f);
                            if(file_exists($wav)){
                                if(file_get_contents($f) == md5_file($wav)){
                                   $this->all[] = $wav;
                                }
                            }
                            //var_dump($pathinfo);exit;
                        } 
                        //$this->all[$f] = md5_file($f);
                    }  elseif (is_dir($f)) {
                        $this->dir_file($f);
                    }  */
                }
            }
        }
        return $this->all;
    }
    public function fileList(){
        $path = input('path/s');
        $dir = '/home/wwwroot/default/recording_data';
        if($path){
            $dir.='/'.$path; 
        }
      //  echo 1;exit;
        $files = $this->dir_file($dir);
        $new_dir = '/home/wwwroot/default/recording_data/';
        
        if(!is_dir($new_dir)){
            mkdir($new_dir);
        }
        return resultArray(['data'=>$files]);exit;
        /* foreach ($files as $value) {
            $pathinfo = pathinfo($value);
            $new_file = $new_dir.$pathinfo['basename'];
            if($pathinfo['basename']){
                $f = Db::name('files')->where(array('file_name' => $pathinfo['basename']))->find();
                if(empty($f)){
                    $arr = explode('_',$pathinfo['basename']);
                    $meeting_id = $arr[0];
                    $path = $new_file;
                    $wav = $pathinfo['basename'];
                   // var_dump($wav,$path);exit;
                    if($meeting_id && $path && $wav){
                        Db::name('files')->insert(array('file_name'=>$wav));
                        $this->uploadfile_auto($path,$wav,$meeting_id);
                    }
                  
                }
            }
        } */
    }

}
